package com.seata.orderseata.controller;


import com.seata.orderseata.domain.User;
import com.seata.orderseata.service.UserService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author business
 * @since 2023-04-02
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    UserService userService;

    @Resource
    RestTemplate restTemplate;

    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping("saveOrderUser")
    @GlobalTransactional
    public Map saveOrderUser(@RequestBody User user) {
        Map map = new HashMap<>();
        if (userService.save(user)) {
            //调用stock_seata
            List<ServiceInstance> instances = discoveryClient.getInstances("stock");
            ServiceInstance serviceInstance = instances.get(0);
            URI uri = serviceInstance.getUri();
            String tageUrl = uri + "/user/saveStockUser";

            map = restTemplate.postForObject(tageUrl, user, Map.class);
        }
        return map;
    }
}

